package com.jtcoding.chat.model;

import com.jtcoding.chat.common.enums.ResultCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;

/**
 * 统一API的返回格式 ，并使用Swagger描述API返回信息
 * 
 * @author Sky.Pang
 * @created Jun 26, 2018
 * @describe 
*/

@ApiModel(description = "API请求的回复信息类")
@Data
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
	
	@ApiModelProperty(value = "状态码", example = "ok", position = 1)
	private String code;
	@ApiModelProperty(value = "状态消息", example = "success", position = 2)
	private String message;
	@ApiModelProperty(value = "回复实体数据", position = 3)
	private T data;
	
	private void setResult(ResultCode resultCode) {
		this.code = resultCode.code();
		this.message = resultCode.msg();
	}
	
	/* 请求成功，没有实体信息返回，只返回成功状态  */
	public static <T> Result<T> success() {
		Result<T> result = new Result<T>();
		result.setResult(ResultCode.SUCCESS);
		return result;
	}
	
	/* 请求成功，返回实体信息 */ 
	public static <T> Result<T> success(T data) {
		Result<T> result = new Result<T>();
		result.setResult(ResultCode.SUCCESS);
		result.setData(data);
		return result;
	}
	
	/* 出现错误，只返回错误信息 */ 
	public static <T> Result<T> failure(ResultCode resultCode) {
		Result<T> result = new Result<T>();
		result.setResult(resultCode);
		return result;
	}
	
	/* 出现错误，返回错误信息和实体信息 */ 
	public static <T> Result<T> failure(ResultCode resultCode, T data) {
		Result<T> result = new Result<T>();
		result.setResult(resultCode);
		result.setData(data);
		return result;
	}

	/* 出现错误，返回错误信息 */
	public static <T> Result<T> failure(String errMsg) {
		Result<T> result = new Result<T>();
		result.setCode("E000");
		result.setMessage(errMsg);
		return result;
	}
	
}
